package com.drore.logapp.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;


/**
 * 判断当前网络环境的工具类
 * 
 * @author CBS
 * 
 */
public class NetUtils {
	/**
	 * 检查当前网络是否可用
	 *
	 * @return 是否连接到网络
	 */
	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		if (connectivityManager != null) {
			NetworkInfo info = connectivityManager.getActiveNetworkInfo();
			if (info != null && info.isConnected()) {
				if (info.getState() == NetworkInfo.State.CONNECTED) {
					return true;
				}
			}
		}
		return false;
	}
	/**
	 * 获取网络状态
	 * 
	 * @param context
	 * @return 已连接返回true, 否则返回false
	 */
	public static boolean checkNetWork(Context context) {
		boolean isWifi = isWifi(context);
		boolean isMobile = isMobile(context);
		if (!isWifi && !isMobile) {
			return false;
		}
		return true;
	}

	/**
	 * 判断是否为Mobile联网
	 * 
	 * @param context
	 * @return true 当前网络环境为Mobile方式联网，反之false
	 */
	public static boolean isMobile(Context context) {
		if(context != null){
			ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			return networkInfo != null ? networkInfo.isConnected() : false;
		}else{
			return false;
		}
	}

	/**
	 * 判断是否是Wifi联网
	 * 
	 * @param context
	 * @return true 当前网络环境为Wifi联网， 反之false
	 */
	public static boolean isWifi(Context context) {
		if(context != null){
			ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			return networkInfo != null ? networkInfo.isConnected() : false;
		}else{
			return false;
		}
	}

}
